﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using HZU.ZP.Domain.IService;
using HZU.ZP.Domain.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HZU.ZP.Controllers
{
    public class NoticeController : Controller
    {
        private INoticeService _noticeService;
        private ICommentService _commentService;
        private IZanService _zanService;
        private ICompanyService _companyService;
        private IApplicantService _applicantService;
        private IAdminService _adminService;
        private IHostingEnvironment _hostingEnv;
        public NoticeController(INoticeService noticeService, ICommentService commentService,
            IZanService zanService, ICompanyService companyService,
            IApplicantService applicantService, IAdminService adminService,
            IHostingEnvironment env)
        {
            _noticeService = noticeService;
            _commentService = commentService;
            _zanService = zanService;
            _companyService = companyService;
            _applicantService = applicantService;
            _adminService = adminService;
            _hostingEnv = env;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public IActionResult AddNotice()
        {
            ViewData["Title"] = "添加公告";
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public IActionResult AddNotice([FromBody]Notice notice)
        {
            _noticeService.Add(notice);
            return Json(AjaxResult.ReturnMessage(1, "添加成功"));
        }

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public IActionResult UpdateNotice(int id)
        {           
            Notice notice = _noticeService.GetById(id);
            if (notice == null)
                return NotFound();

            ViewData["Title"] = "更新公告";
            return View(notice);
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public IActionResult UpdateNotice(int id, string title, string content)
        {           
            Notice notice = _noticeService.GetById(id);
            notice.Title = title;
            notice.Content = content;
            _noticeService.Update(notice);
            return Json(AjaxResult.ReturnMessage(1, "更新成功"));
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public IActionResult DeleteNotice(int id)
        {            
            _noticeService.Delete(id);
            return Json(AjaxResult.ReturnMessage(1, "删除成功"));
        }

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public IActionResult NoticeList(int pageIndex = 1)
        {
            IList<Notice> notices = new List<Notice>();
            notices = _noticeService.GetList(pageIndex);
            int pageCount = (int)Math.Ceiling((double)_noticeService.GetCount() / 20);
            ViewData["PageCount"] = pageCount;
            if (pageCount == 0)
            {
                ViewData["PageIndex"] = 0;
            }
            else
            {
                ViewData["PageIndex"] = pageIndex;
            }
            ViewData["Title"] = "公告列表";
            return View(notices);
        }

        [Authorize]
        [HttpGet]
        public IActionResult GetNotice(int noticeId, string email)
        {
            int pageSize = 1;
            int userId = 0;
            //获取公告信息
            NoticeView noticeView = new NoticeView();
            noticeView.Notice = _noticeService.GetById(noticeId);
            if (noticeView.Notice == null)
                return NotFound();
            noticeView.Notice.PraisePoints = _zanService.GetZanCount(noticeId);
            //获取公告的评论
            noticeView.Comments = _commentService.GetByNoticeId(noticeId, pageSize);
            int count = _commentService.GetByNoticeCount(noticeId);
            ViewData["Count"] = count;
            int pageCount = (int)Math.Ceiling((double)count / 10);
            ViewData["PageCount"] = pageCount;
            if (pageCount == 0)
            {
                ViewData["PageIndex"] = 0;
            }
            else
            {
                ViewData["PageIndex"] = 1;
            }
            //获取用户是否点赞
            switch (User.Claims.ToList()[2].Value)
            {
                case "Admin":
                    userId = _adminService.GetAdmin(email).Id.Value;
                    break;
                case "Company":
                    userId = _companyService.GetByEmail(email).Id.Value;
                    break;
                case "Applicant":
                    userId = _applicantService.GetApplicant(email).Id.Value;
                    break;
            }
            noticeView.Zan = _zanService.GetZan(noticeId, userId, User.Claims.ToList()[2].Value);
            ViewData["Title"] = "公告详情";
            return View(noticeView);
        }

        /// <summary>
        /// 上传图片,通过Form表单提交
        /// </summary>
        /// <returns></returns>        
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult UploadImg(IFormFileCollection files)
        {
            if (files.Count == 0)
            {
                return Json(new { returnCode = "400" });
            }
            //返回的文件地址
            List<string> filenames = new List<string>();
            var now = DateTime.Now;
            //文件存储路径
            var filePath = string.Format("/Notice/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            //获取当前web目录
            var webRootPath = _hostingEnv.WebRootPath;
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }
            try
            {
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        #region  图片文件的条件判断
                        //文件后缀
                        var fileExtension = Path.GetExtension(item.FileName);

                        //判断后缀是否是图片
                        const string fileFilt = ".gif|.jpg|.jpeg|.png";
                        if (fileExtension == null)
                        {
                            break;
                            //return Error("上传的文件没有后缀");
                        }
                        if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                        {
                            break;
                            //return Error("请上传jpg、png、gif格式的图片");
                        }

                        //判断文件大小    
                        long length = item.Length;
                        if (length > 1024 * 1024 * 6) //2M
                        {
                            break;
                            //return Error("上传的文件不能大于2M");
                        }

                        #endregion

                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        var saveName = strDateTime + strRan + fileExtension;

                        //插入图片数据                 
                        using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }
                        filenames.Add(filePath + saveName);
                    }
                }
                Result result = new Result();
                result.Errno = 0;
                result.Data = filenames;
                return Json(result);
            }
            catch (Exception ex)
            {
                //这边增加日志，记录错误的原因
                //ex.ToString();
                return Json(AjaxResult.ReturnMessage(1, "上传失败"));
            }
        }
    }
}
